package it.totaltecnica.fatture.dao;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;


@Repository
@Transactional
public class GenericDao<T> {
	private Class<T> entityClass;
	private EntityManager entityManager;

	public GenericDao() {
		super();
	}

	public GenericDao(Class<T> entityClass) {
		super();
		this.entityClass = entityClass;
	}

	/**
	 * 
	 * @param id
	 * @return
	 */
	public T getItemByID(Serializable id) {
		return entityManager.find(entityClass, id);
	}
	
	/**
	 * 
	 * @param query
	 * @param params
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public T getItem(String queryName, Map<String, String> params) {

		Query query = entityManager.createNamedQuery(queryName);
		
		for(String key : params.keySet()) {
			query.setParameter(key, params.get(key));
		}
		
		List<?> resultList = query.getResultList();
		
		if(resultList.size() >0)
			return (T) resultList.get(0);
		return null;
	}

	/**
	 * 
	 * @param instance
	 * @return
	 */
	public T updateItem(T instance) {
		return entityManager.merge(instance);
	}


	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	protected EntityManager getEntityManager() {
		return entityManager;
	}

}
